<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏大厅</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_hall.css">
</head>
<body>
    <div class="nav">
        <img src="pic/logo.jpg" alt="">
        <span class="title">五子棋</span>
        <div class="space"></div>
        <a class="nav-span" href="login.html" onclick="logout()">登出</a>
    </div>
    <!-- 整个页面的容器元素 -->
    <div class="container">
        <!-- 这个 div 在 container 中是处于垂直水平居中这样的位置的 -->
        <div>
            <div id="screen"></div>
            <div id="match-button">开始匹配</div>
        </div>
    </div>

    <script src="js/jquery.min.js"></script>
    <script>
        $.ajax({
            type: 'get',
            url: '/user/userInfo',
            success: function(body) {
                let screenDiv = document.querySelector('#screen');
                if(body != null && body.code === 200 && body.data != null) {
                    let user = body.data;
                    screenDiv.innerHTML = "玩家: " + user.username + "<br> 分数: " + user.score
                        + "<br> 获胜场数: " + user.winCount + "<br> 比赛场次: " + user.totalCount;
                }
            },
            error: function() {
                alert("获取用户信息失败!");
            }
        });

        // 此处进行初始化 websocket, 并且实现前端的匹配逻辑
        let websocketUrl = 'ws://' + location.host + '/findMatch'; //让url适配不同服务器ip
        let websocket = new WebSocket(websocketUrl);
        websocket.onopen = function() {
            console.log("onopen");
        }
        websocket.onclose = function() {
            console.log("onclose");
        }
        websocket.onerror = function() {
            console.log("onerror");
        }
        // 监听页面关闭事件. 在页面关闭之前, 手动调用这里的 websocket 的 close 方法. 
        window.onbeforeunload = function() {
            websocket.close();
        }

        websocket.onmessage = function(result) {
            // 处理服务器返回的响应数据. 这个响应就是针对 "开始匹配" / "结束匹配" 来对应的
            // 解析得到的响应对象. 返回的数据是一个 JSON 字符串, 解析成 js 对象
            // 此处是WebSocket通信，没有spring统一返回
            if(result != null) {
                let resp = JSON.parse(result.data);
                let matchButton = document.querySelector('#match-button');
                if (!resp.ok) {
                    console.log("!resp.ok: " + resp.reason);
                    return;
                }
                if (resp.message === 'startMatch') {
                    // 开始匹配请求发送成功
                    console.log("进入匹配队列");
                    matchButton.innerHTML = '匹配中...';
                } else if (resp.message === 'stopMatch') {
                    // 结束匹配请求发送成功
                    console.log("离开匹配队列");
                    matchButton.innerHTML = '开始匹配';
                } else if (resp.message === 'matchSuccess') {
                    // 已经匹配到对手了.
                    console.log("进入游戏房间");
                    location.href = "/game_room.html";
                } else if (resp.message === 'repeatConnection') {
                    alert("同一用户无法多次登录");
                    location.href = "/login.html";
                } else {
                    console.log("response error, message=" + resp.message);
                }
            }
        }

        let matchButton = document.querySelector('#match-button');
        matchButton.onclick = function() {
            // 在触发 websocket 请求之前, 先确认下 websocket 连接是否好着呢~~ 
            if (websocket.readyState === websocket.OPEN) {
                if (matchButton.innerHTML === '开始匹配') {
                    websocket.send(JSON.stringify({
                        message: 'startMatch',
                    }));
                } else if (matchButton.innerHTML === '匹配中...') {
                    websocket.send(JSON.stringify({
                        message: 'stopMatch',
                    }));
                }
            } else {
                alert("连接已断开");
                location.replace('/login.html'); //页面跳转，WebSocket连接关闭
            }
        }
    </script>
</body>
</html>